package com.aly.beanValidate.core;

import com.aly.beanValidate.i.BeanInfo;
import com.aly.beanValidate.i.FileInfo;
import com.aly.beanValidate.i.FileInfos;
import com.aly.game.util.StringUtils;
import org.dom4j.Element;

import java.util.HashMap;
import java.util.Map;

/**
 * 校验配置
 */
public class BeanDefinition {
    private String fileName;
    private Map<String, FieldConfigs> fieldValidators = new HashMap<>();

    public BeanDefinition(String name, Element model, GlobalConfigs globalConfigs) throws Exception {
        this.fileName = name;
        for (Element field : model.elements()) {
            if ("field".equals(field.getName())) {
                String fieldName = Util.attr(field, "name");
                FieldDefinition definition = new FieldDefinition(field);
                FieldConfigs old = fieldValidators.put(fieldName.toLowerCase(), new FieldConfigs(definition,field, globalConfigs));
                if (null != old) {
                    throw new RuntimeException(fileName + "中 重复定义了字段" + fieldName);
                }
            }
        }
    }

    public Map<String, FieldConfigs> getFieldValidators() {
        return fieldValidators;
    }

    public String getFileName() {
        return fileName;
    }

    public StringBuffer validate(BeanInfo bean, FileInfo fileInfo, FileInfos fileInfos) {
        StringBuffer sb = new StringBuffer();
        for (Map.Entry<String, FieldConfigs> entry : fieldValidators.entrySet()) {
            String field = entry.getKey();
            String val = bean.getFieldValue(field);

            StringBuffer ret = entry.getValue().validate( val, bean, fileInfo, fileInfos);
            if (StringUtils.isNotEmpty(ret)) {
                sb.append("\tField:[").append(field).append("] val:[").append(val).append("]").append(ret);
            }
        }
        if (sb.length() > 0) {
            sb.insert(0, fileName + "校验错误:");
        }
        return sb;
    }
}
